package models

import (
	"database/sql"
	"errors"
	"time"
)

type AdminModel struct {
	Id       int64  `db:"id"`
	Name     string `db:"name"`
	Account  string `db:"account"`
	Password string `db:"password"`
	Sex      uint8  `db:"sex"`
	Avatar   string `db:"avatar"`
	GroupId	 int64`db:"group_id"`
	CreateAt int64  `db:"create_at"`
	UpdateAt int64  `db:"update_at"`
}

type Promise struct {
	Path string`json:"path"`
	Value int`json:"value"`
}

func GetAdminByAccount(db *sql.DB, account string) (*AdminModel, error) {
	sqlStr := "SELECT * FROM `u_admin` WHERE `account` = ? limit 1"
	stmt, err := db.Prepare(sqlStr)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()
	rows, err := stmt.Query(account)
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var admin = new(AdminModel)
		err = rows.Scan(admin.Id, admin.Account, admin.Name, admin.Password, admin.Avatar, admin.Sex, admin.CreateAt, admin.UpdateAt)
		if err != nil {
			return nil, err
		}
		return admin, nil
	}
	return nil, errors.New("not fount data")
}

func GetAdminPassword(db *sql.DB, account string) (int64, string, error) {
	sqlStr := "SELECT id,password FROM `u_admin` WHERE `account` = ? limit 1"
	stmt, err := db.Prepare(sqlStr)
	if err != nil {
		return 0, "", err
	}
	defer stmt.Close()
	row := stmt.QueryRow(account)
	var password = ""
	var id int64
	err = row.Scan(&id, &password)
	if err != nil {
		return 0, "", err
	}
	return id, password, nil
}

func CreateAdmin(db *sql.DB, account, password, name string) (bool, error) {
	sqlStr := "INSERT INTO `u_admin` (`account`,`name`,`password`,`create_at`,`update_at`) VALUES (?,?,?,?,?)"
	stmt, err := db.Prepare(sqlStr)
	if err != nil {
		return false, err
	}
	now := time.Now().Unix()
	res, err := stmt.Exec(account, name, password,now,now)
	if err != nil {
		return false, err
	}
	rows, err := res.RowsAffected()
	if err != nil {
		return false, err
	}
	return rows == 1, nil
}

/**
通过管理员ID查找权限
 */
func GetPromiseByAdminID(db *sql.DB, id int64) ([]Promise, error) {
	sqlStr := `SELECT
					p.path,p.value
				FROM
					u_admin AS a
					RIGHT JOIN u_group_role AS gr ON gr.group_id = a.group_id
					RIGHT JOIN u_role_promise AS rp ON rp.role_id = gr.role_id
					RIGHT JOIN u_promises AS p ON rp.promise_id = p.id 
				WHERE
					a.id =  ?
				GROUP BY
					p.id`
	rows,err := db.Query(sqlStr,id)
	if err != nil {
		return nil, err
	}
	var promises []Promise
	for rows.Next() {
		promise := Promise{}
		err = rows.Scan(&promise.Path,promise.Value)
		if err != nil {
			return nil, err
		}
		promises = append(promises,promise)
	}
	return promises,err
}